<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        @submit.native.prevent
        label-width="65px"
      >
        <el-form-item label="规则名称" prop="ruleName">
          <common-input
            v-model="queryParams.ruleName"
            placeholder="请输入"
            @enter="handleQuery"
          ></common-input>
        </el-form-item>
        <!-- <el-form-item label="敏感字段" prop="wordNames">
          <common-input
            v-model="queryParams.wordNames"
            placeholder="请输入"
          ></common-input>
        </el-form-item> -->
        <el-form-item label="敏感字段" prop="wordNames">
          <el-select v-model="queryParams.wordNames">
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in wordsList"
              :label="item.name"
              :value="item.name"
              :key="item.wordId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="启用" value="0"> </el-option>
            <el-option label="停用" value="1"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>
    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          data-test="rule_variable-button-add"
          v-hasPermi="['datahandler:discernrule:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleDelete()"
          :disabled="ids.length < 1"
          v-hasPermi="['datahandler:discernrule:remove']"
          >批量删除
        </el-button>
      </el-col>
    </el-row>
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规则名称" prop="ruleName" show-overflow-tooltip />
      <el-table-column
        label="敏感字段"
        align="left"
        prop="wordNames"
        show-overflow-tooltip
      />
      <el-table-column
        label="备注"
        align="left"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column width="80px" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="success">启用</el-tag>
          <el-tag v-if="scope.row.status === 1" type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="160">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">
            详情
          </el-button>
          <el-button
            type="text"
            @click="handleShake(scope.row)"
            :disabled="scope.row.isDisabledForShake"
            v-hasPermi="['datahandler:discernrule:updateStatus']"
          >
            <span v-if="scope.row.status === 1">启用</span>
            <span v-if="scope.row.status === 0">停用</span>
          </el-button>
          <el-button
            type="text"
            @click="handleEdit(scope.row)"
            v-hasPermi="['datahandler:discernrule:edit']"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datahandler:discernrule:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <common-edit-dialog
      :visible.sync="isEditCell"
      @cancel="isEditCell = false"
      @submit="submit"
      :button-loading="submitLoading"
      :title="title ? '新增识别规则' : '编辑识别规则'"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="规则名称" prop="ruleName">
              <common-input
                v-model="form.ruleName"
                :maxlength="16"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="敏感字段" prop="wordIds">
              <el-checkbox-group v-model="form.wordIds">
                <el-checkbox
                  style="margin-bottom: 8px"
                  v-for="item in bindCheckAll"
                  :key="item.wordId"
                  :label="item.wordId"
                >
                  <el-tooltip
                    :disabled="isShowTooltip"
                    effect="dark"
                    :content="item.name"
                    placement="top"
                  >
                    <span
                      style="
                        display: inline-block;
                        width: 110px;
                        overflow: hidden;
                        vertical-align: top;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                      "
                      @mouseenter="visibilityChange($event)"
                      >{{ item.name }}</span
                    ></el-tooltip
                  >
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="识别逻辑"
              prop="discernRule"
              v-if="form.wordIds && form.wordIds.length > 1"
            >
              <el-radio v-model="form.discernRule" label="0">与</el-radio>
              <el-radio v-model="form.discernRule" label="1">或</el-radio>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注">
              <common-input
                v-model="form.remark"
                placeholder="请输入"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
    <common-info-dialog :visible.sync="infoShow" @cancel="infoShow = false">
      <common-info-table>
        <common-info-table-cell label="规则名称">{{
          info.ruleName
        }}</common-info-table-cell>

        <common-info-table-cell label="敏感字段">{{
          info.wordNames
        }}</common-info-table-cell>
        <common-info-table-cell
          label="识别逻辑"
          v-if="info.wordIds && info.wordIds.length > 1"
          >{{ info.discernRule === 0 ? "与" : "或" }}</common-info-table-cell
        >
        <common-info-table-cell label="状态">{{
          info.status === 0 ? "启用" : "停用"
        }}</common-info-table-cell>
        <common-info-table-cell label="备注">{{
          info.remark
        }}</common-info-table-cell>
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
import BaseList from "@/mixins/BaseList";
import {
  queryList,
  updateStatus,
  queryListForType,
  queryAdd,
  queryUpdate,
  queryDelete,
} from "@/api/datahandler/discernRule";
import { querySensitiveAllWordsList } from "@/api/datascan/scanresults/column";
export default {
  name: "discernRule",
  mixins: [BaseList],
  data() {
    return {
      list: [],
      ids: [],
      loading: false,
      total: 0,
      bindCheckAll: [],
      infoShow: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: "",
        wordNames: null,
        status: null,
      },
      form: {
        id: "",
        ruleName: "",
        wordIds: [],
        status: "",
        discernRule: "0",
        remark: "",
      },
      rules: {
        ruleName: [
          { required: true, message: "请输入规则名称", trigger: "blur" },
        ],
        wordIds: [
          { required: true, message: "请选择敏感字段", trigger: "blur" },
        ],
        discernRule: [
          { required: true, message: "请选择识别逻辑", trigger: "blur" },
        ],
      },
      isEditCell: false,
      title: false,

      submitLoading: false,
      info: {},
      wordsList: [],
      isShowTooltip: false,
    };
  },
  methods: {
    visibilityChange(event) {
      const ev = event.target;
      const ev_weight = ev.scrollWidth;
      const content_weight = ev.clientWidth;
      if (ev_weight > content_weight) {
        this.isShowTooltip = false;
      } else {
        // 否则为不溢出
        this.isShowTooltip = true;
      }
    },
    //列表
    getList() {
      this.loading = true;
      queryList({ ...this.queryParams })
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                isDisabledForShake: false,
              });
              return r;
            }, []);
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    //启停
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        let params = {
          id: row.id,
          status: row.status === 1 ? 0 : 1,
        };
        updateStatus(params)
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("操作成功");
              resolve(res);
              this.list.find((item) => {
                return item.id === row.id;
              }).status = row.status === 1 ? 0 : 1;
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg).then();
              reject();
            }
          })
          .catch(() => reject());
      });
    },
    //查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //重置
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    //新增
    handleAdd() {
      this.isEditCell = true;
      this.title = true;
      this.form = {
        id: "",
        ruleName: "",
        wordIds: [],
        status: "",
        discernRule: "0",
        remark: "",
      };
      this.getListForType();
    },
    //编辑
    handleEdit(row) {
      if (row.status === 0) {
        //启用状态
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      } else {
        this.isEditCell = true;
        this.title = false;
        this.form.wordIds = [];
        this.getListForType(row);
      }
    },
    //敏感数据
    getListForType(row) {
      queryListForType().then((res) => {
        if (res && res.code === 200) {
          this.bindCheckAll = res.data.dataList.reduce((r, c) => {
            r.push({ wordId: c.wordId.toString(), name: c.name });
            return r;
          }, []);
          if (row) {
            Reflect.ownKeys(this.form).forEach((k) => (this.form[k] = row[k]));

            this.form.wordIds = row?.wordIds ? row.wordIds.split(",") : [];
            this.form.discernRule = this.form?.discernRule.toString();
          }
        } else {
          this.$GlobalErrorConfirm("数据加载失败", res.msg);
        }
      });
    },
    handleDelete(row) {
      if (row) {
        //单选
        if (row.status === 0) {
          //启用状态
          this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        } else {
          const ids = row?.id;
          this.$GlobalDeleteConfirm()
            .then(() => {
              queryDelete({ ids }).then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("删除成功");
                  if (
                    this.queryParams.pageNum > 1 &&
                    ids.split(",").length === this.list.length
                  ) {
                    this.queryParams.pageNum -= 1;
                  }
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("删除失败", res.msg);
                }
              });
            })
            .catch(() => {});
        }
      } else {
        //多选
        let status = this.list.find(
          (v) => this.ids.includes(v.id) && v.status === 0
        );

        if (status) {
          return this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        } else {
          const ids = this.ids.join(",");
          this.$GlobalDeleteConfirm()
            .then(() => {
              queryDelete({ ids }).then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("删除成功");
                  if (
                    this.queryParams.pageNum > 1 &&
                    ids.split(",").length === this.list.length
                  ) {
                    this.queryParams.pageNum -= 1;
                  }
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("删除失败", res.msg);
                }
              });
            })
            .catch(() => {});
        }
      }
    },

    //详情
    handleView(row) {
      this.infoShow = true;
      this.info = row;
    },

    //提交
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          if (this.title) {
            let query = {
              ...this.form,
              wordIds: this.form.wordIds.join(","),
            };

            queryAdd(query)
              .then((res) => {
                if (res && res.code === 200) {
                  this.isEditCell = false;
                  this.$GlobalSuccessMessage("新增成功");
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                  this.handleListTips(res);
                }
              })
              .finally(() => {
                this.submitLoading = false;
              });
          } else {
            let query = {
              ...this.form,
              wordIds: this.form.wordIds.join(","),
              id: this.form.id,
            };
            queryUpdate(query)
              .then((res) => {
                if (res && res.code === 200) {
                  this.isEditCell = false;
                  this.$GlobalSuccessMessage("编辑成功");
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                  this.handleListTips(res);
                }
              })
              .finally(() => {
                this.submitLoading = false;
              });
          }
        }
      });
    },
    getSensitiveAllWordsList() {
      querySensitiveAllWordsList().then((res) => {
        if (res && res.code === 200) {
          this.wordsList = res.data.dataList;
        } else {
          this.wordsList = [];
        }
      });
    },
  },
  mounted() {
    this.getList();
    this.getSensitiveAllWordsList();
  },
};
</script>
<style lang="scss" scoped></style>
